#include "widget.h"
#include "ui_widget.h"
#include <QDataStream>
#include <QMessageBox>
#include <QTime>
#include <QToolButton>
#include <QColorDialog>
#include <QFileDialog>

Widget::Widget(QWidget *parent, QString name)
    : QWidget(parent)
    , ui(new Ui::Widget)
{

    ui->setupUi(this);
    myName = name;
    this->setWindowTitle(myName);

    this->port = 9999;
    this->udpSocket = new QUdpSocket(this);

    // 绑定端口和套接字
    udpSocket->bind(port,QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);

    // 监听信号
    connect(udpSocket,&QUdpSocket::readyRead,this,&Widget::ReceiveMessage);

    // 连接发送按钮
    connect(ui->sendBtn,&QPushButton::clicked,[=](){
        sendMsg(Msg);
    });

    // 新用户进入
    sendMsg(UserEnter);

    // 退出按钮
    connect(ui->exitBtn,&QPushButton::clicked,[=](){
        this->close();
    });

    // 字体选择
    connect(ui->fontComboBox,&QFontComboBox::currentFontChanged,[=](const QFont &font){
        ui->textEdit->setFontFamily(font.toString());
        ui->textEdit->setFocus();
    });

    // 字体大小
    void (QComboBox:: * sizeBtn )(const QString &text) = &QComboBox::currentTextChanged;
    connect(ui->fontComboBox_2, sizeBtn,[=](const QString &text){
        ui->textEdit->setFontPointSize(text.toDouble());
        ui->textEdit->setFocus();
    });

    // 加粗
    connect(ui->overstrikingBtn,&QToolButton::clicked,[=](bool checked){
        if(checked){
            ui->textEdit->setFontWeight(QFont::Bold);
        }
        else
        {
            ui->textEdit->setFontWeight(QFont::Normal);
        }
    });

    // 倾斜
    connect(ui->inclineBtn,&QToolButton::clicked,[=](bool checked){
        ui->textEdit->setFontItalic(checked);
        ui->textEdit->setFocus();
    });

    // 下划线
    connect(ui->underlineBtn,&QToolButton::clicked,[=](bool checked){
        ui->textEdit->setFontUnderline(checked);
        ui->textEdit->setFocus();
    });

    // 清空
    connect(ui->clearBtn, &QToolButton::clicked,[=](){
        ui->messageWidget->clear();
    });

    // 字体设置文本颜色
    connect(ui->colorBtn, &QToolButton::clicked,[=](){
        QColor color = QColorDialog::getColor(color,this);

        ui->textEdit->setTextColor(color);

    });

    // 文件保存 保存聊天记录
    connect(ui->saveBtn, &QToolButton::clicked,[=](){
        if(ui->messageWidget->toPlainText().isEmpty()){
            QMessageBox::warning(this, "警告","保存内容不能为空!!!");
            return;
        }
        QString fileName = QFileDialog::getSaveFileName(this, "保存聊天记录","聊天记录","(*.txt)");

        if(!fileName.isEmpty()){
            QFile file(fileName);
            file.open(QIODevice::WriteOnly | QFile::Text);
            QTextStream stream(&file);
            stream << ui->messageWidget->toPlainText();
            file.close();
        }
    });

}

// 重写关闭事件
void Widget::closeEvent(QCloseEvent *){
    emit this->closeWidget();

    sendMsg(UserLeft);

    udpSocket->close();
    udpSocket->destroyed();
}

QString Widget::getName(){
    return this->myName;
}

QString Widget::getMsg(){
    QString msg = ui->textEdit->toHtml(); // 返回输入框的内容
    ui->textEdit->clear(); // 将内容清空
    ui->textEdit->setFocus(); // 设置光标
    return msg;
}

void Widget::sendMsg(Msgtype type){
    QByteArray array;
    QDataStream stream(&array,QIODevice::WriteOnly);

    stream << type << this->getName();

    switch(type){
    case Msg:
        if(ui->textEdit->toPlainText()==""){
            QMessageBox::warning(this,"警告","发送内容不能为空!!!");
            return;
        }
        stream << this->getMsg();
        break;

    case UserEnter:


        break;

    case UserLeft:
        break;

    }

    // 书写报文
    udpSocket->writeDatagram(array.data(),array.size(),QHostAddress::Broadcast,this->port);

}

void Widget::userEnter(QString username){
    bool IsEmpty = ui->tableWidget->findItems(username, Qt::MatchExactly).isEmpty();

    if(IsEmpty){
        QTableWidgetItem * table = new QTableWidgetItem(username);
        ui->tableWidget->insertRow(0);
        ui->tableWidget->setItem(0,0,table);
        ui->messageWidget->setTextColor(QColor(Qt::gray));
        ui->messageWidget->append(username + "已上线");
        ui->onlineNumLabel->setText(QString("在线人数: %1").arg(ui->tableWidget->rowCount()));

        // 不加这个的话，新用户的在线人数表格永远只有字节的
        sendMsg(UserEnter);
    }

}
void Widget::userLeft(QString username, QString time){
    bool IsEmpty = ui->tableWidget->findItems(username, Qt::MatchExactly).isEmpty();

    if(!IsEmpty){
        // 寻找离开用户的信息在哪一行
        int row = ui->tableWidget->findItems(username, Qt::MatchExactly).first() -> row();

        // 移除该行
        ui -> tableWidget->removeRow(row);

        // 追加信息
        ui->messageWidget->setTextColor(Qt::gray);
        ui->messageWidget->append(username + "用户于" + time + "下线");
        ui->onlineNumLabel->setText(QString("在线人数:%1人").arg(ui->tableWidget->rowCount()));

    }

}
void Widget::ReceiveMessage(){
    qint64 size = udpSocket->pendingDatagramSize();

    int mysize = static_cast<int>(size);
    QByteArray * array = new QByteArray(mysize,0);

    // 读报文
    udpSocket->readDatagram((*array).data(),size);

    QDataStream stream(array,QIODevice::ReadOnly);
    int mytype;

    QString name, msg; // 用户名 聊天内容
    QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    stream >> mytype;
    switch(mytype){
    case Msg:
        stream >> name >> msg;
        ui->messageWidget->setTextColor(QColor(Qt::blue));
        ui->messageWidget->append("[" + name + "]"+ time);
        ui->messageWidget->append(msg);
        break;

    case UserEnter:
        stream >> name;
        userEnter(name);

        break;

    case UserLeft:
        stream >> name;
        userLeft(name, time);

        break;
    }
}

Widget::~Widget()
{
    delete ui;
}
